<?php


namespace App\Utils;

use App\Exceptions\BusinessException;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

trait VerifyRequestInput
{
    /**
     * 验证ID
     * @param string $key
     * @param null $default
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyId(string $key, $default = null): mixed
    {
        return $this->verifyData($key, $default, 'integer|digits_between:1,20');
    }

    /**
     * 验证是否为整数
     * @param string $key
     * @param null $default
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyInteger(string $key, $default = null): mixed
    {
        return $this->verifyData($key, $default, 'integer');
    }

    /**
     * 验证是否为数字
     * @param string $key
     * @param null $default
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyNumeric(string $key, $default = null): mixed
    {
        return $this->verifyData($key, $default, 'numeric');
    }

    /**
     * 验证是否为字符串
     * @param string $key
     * @param null $default
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyString(string $key, $default = null): mixed
    {
        return $this->verifyData($key, $default, 'string');
    }

    /**
     * 验证是否为布尔值
     * @param string $key
     * @param null $default
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyBoolean(string $key, $default = null): mixed
    {
        return $this->verifyData($key, $default, 'boolean');
    }

    /**
     * 验证是否为枚举
     * @param string $key
     * @param null $default
     * @param array $enum
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyEnum(string $key, $default = null, array $enum = []): mixed
    {
        return $this->verifyData($key, $default, Rule::in($enum));
    }

  /**
   * 自定义校验参数
   * @param string $key
   * @param string|null $default
   * @param string $rule
   * @return mixed
   * @throws BusinessException
   */
    public function verifyData(string $key, ?string $default, string $rule): mixed
    {
        $value = request()->input($key, $default);
        $validator = Validator::make([$key => $value], [$key => $rule]);
        if (is_null($value)){
            $this->throwBusinessException(ResponseEnum::CLIENT_PARAMETER_ERROR);
        }
        if ($validator->fails()){
            $this->throwBusinessException(ResponseEnum::CLIENT_PARAMETER_ERROR, $validator->errors()->first());
        }
        return $value;
    }
}
